// UserStore.ts
import { defineStore } from 'pinia';
import { io, Socket } from 'socket.io-client';
// @ts-ignore
import { DemoLogin } from '@/api/index'
// @ts-ignore
import { getFriendsList } from '@/api/index';

// 已登录用户状态管理
export const useUserStore = defineStore('user', {
    state: () => ({
        userObj: {} as any,
        // ... 其他用户状态字段...
    }),
    actions: {
        // 登录成功后设置userId
        async setUserIdAfterLogin(payload: { username: string, password: string }) {
            const userInfo = {
                username: payload.username,
                password: payload.password
            };

            const response = DemoLogin(userInfo)
                .then((res: any) => {
                    // console.log('pinia setUserIdAfterLogin', res);
                    this.$state.userObj = res.data;
                })
                .catch((err: any) => {
                    console.log('pinia setUserIdAfterLogin', err);
                })
            // console.log('pinia setUserIdAfterLogin', response);
        },
    },
});

// 好友列表状态管理
export const useFriendListStore = defineStore('friendList', {
    state: () => ({
        friendList: [] as any[],
    }),
    actions: {
        // 可以考虑在loadFriendList方法内部添加一个回调函数，用于通知外部数据已加载完成
        async loadFriendList(callback?: () => void) {

            const userStore = useUserStore();

            if (userStore.$state.userObj) {
                const response = getFriendsList(userStore.$state.userObj.userId)
                    .then((res: any) => {
                        // console.log('pinia loadFriendList', res.data);
                        this.$state.friendList = res.data;
                        callback?.();

                    })
                    .catch((err: any) => {
                        console.log('pinia loadFriendList', err);
                    })

                // console.log('pinia loadFriendList', response);
            } else {
                console.warn('Cannot load friend list because user ID is not set.');
            }
        },
    },
});

// 聊天记录状态管理 
export const useChatStore = defineStore('chat', {
    state: () => ({
        temporaryChatRecords: [] as any,
        historicalChatRecords: [] as any,
        socket: null as Socket | null,
    }),
    actions: {
        async connectToSocket(payload: {
            senderId: string | null; receiverId: string; content: string;
        }) {

            // // 创建Socket.IO连接
            const socket = io('http://localhost:3334');

            // 发送一条聊天消息
            socket.emit('sendMessage', payload);

            // 监听消息接收事件
            socket.on('messageReceived', (messageReceived) => {
                if (messageReceived.data && messageReceived.data.id) {
                    this.$state.temporaryChatRecords.push({
                        id: messageReceived.data.id,
                        senderId: messageReceived.data.senderId,
                        receiverId: messageReceived.data.receiverId,
                        content: messageReceived.data.content,
                        timestamp: messageReceived.data.timestamp,
                    });
                }

            });

            // 设置socket实例
            this.$state.socket = socket;
        },

        // async fetchHistoricalChatRecords(senderId: string, receiverId: string) {
        //     try {
        //         const response = await axios.get('/api/chat-records', {
        //             params: {
        //                 senderId,
        //                 receiverId,
        //             },
        //         });

        //         if (response.data && Array.isArray(response.data)) {
        //             // 更新历史记录列表
        //             this.$state.historicalChatRecords = response.data;
        //         }
        //     } catch (error) {
        //         console.error('Error fetching historical chat records:', error);
        //     }
        // },
    },
});